package net.learntechnology.ajax;

import java.io.IOException;
import java.io.PrintWriter;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.sql.*;
import java.io.*;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import properties.LoadProperties;
import net.learntechnology.ajax.FileUploadListener.FileUploadStats;
import net.learntechnology.ajax.FileUploadListener.FileUploadStatus;

/**
 * @author Rick Reumann
 * Most of this code based off the great ajax example using prototype ajax javascript
 * found here: http://www.ioncannon.net/java/38/ajax-file-upload-progress-for-java-using-commons-fileupload-and-prototype/
 */
public class AjaxUploadStatusServlet extends HttpServlet {

    public static LoadProperties lp = new LoadProperties();
    public static String dbName = lp.getDatabaseName();
    public static String dbConnIP = lp.getDatabaseConnectionIP();
    public static String dbConnPort = lp.getDatabaseConnectionPort();
    public static String dbUser = lp.getDatabaseUser();
    public static String dbPwd = lp.getDatabasePwd();


    public static String dbPath = "jdbc:mysql://" + dbConnIP + ":" + dbConnPort + "/" + dbName + "?" +
                            "user=" + dbUser +"&password=" + dbPwd;

      public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }

    public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        System.out.println("doPost of AjaxUploadStatusServlet");
       

        if ( "end".equals( request.getParameter("status"))) {
        	System.out.println("end passed as a parameter for final call.");
        }
        
        FileUploadStats stats = (FileUploadStats) request.getSession().getAttribute("FILE_UPLOAD_STATS");
        String stats1 = (String) request.getSession().getAttribute("file_name");
        System.out.println("status of iflenammmmmmmmmmmmmmmmmmmmmmmmmmmmme sesssion"+stats1);
       // if (stats != null)
        
           if(stats!=null){
            response.addHeader("Cache-Control", "no-store, no-cache, must-revalidate");
            response.addHeader("Cache-Control", "post-check=0, pre-check=0");
            response.addHeader("Pragma", "no-cache");
           /* double percentComplete = stats != null ? percentComplete = stats.getPercentComplete() : 0.0;
            long bytesProcessed = stats.getBytesRead();
            long sizeTotal = stats.getTotalSize();
            DecimalFormat decFormatter = new DecimalFormat(".00");
            long elapsedTimeInMilliseconds = stats.getElapsedTimeInMilliseconds();
            double bytesPerMillisecond = bytesProcessed / (elapsedTimeInMilliseconds + 0.00001);
            long estimatedMillisecondsLeft = (long)((sizeTotal - bytesProcessed) / (bytesPerMillisecond + 0.00001));
            String timeLeft = null;String
            if ( ( estimatedMillisecondsLeft/3600 ) > 24 ) {
                timeLeft = (long)(estimatedMillisecondsLeft/3600) + "hours";
            } else {
                Calendar c = new GregorianCalendar();
                long ad =  estimatedMillisecondsLeft - (c.get(Calendar.ZONE_OFFSET)+c.get(Calendar.DST_OFFSET));
                timeLeft = new SimpleDateFormat("HH:mm:ss").format(ad);
            }

            PrintWriter out = response.getWriter();

            out.print("<div class='prog-border'><div class='prog-bar' style='width: " + (percentComplete * 100) + "%;'></div></div>");
            out.print("<table><tr><td class='st' width='250px;'>"+timeLeft+
                        " (at " + decFormatter.format(bytesPerMillisecond) + "kb/sec)</td><td class='st'>"+
                         decFormatter.format((double)bytesProcessed/(1000*1000)) + " MB / "+decFormatter.format((double)sizeTotal/(1000*1000))+" MB ( "+Math.ceil((percentComplete * 100))+"% )</td></tr></table>");
*/
 int flag=0;
              PrintWriter out = response.getWriter();

 String ttt=null;
    //getting the session
             HttpSession ses=request.getSession(false);
 
            if (stats.getCurrentStatus() == FileUploadStatus.DONE ||stats.getCurrentStatus() == FileUploadStatus.ERROR)
            {

               out.print( stats.getCurrentStatus() == FileUploadStatus.DONE ? "<b></b>" : "<b>Error!</b>");


               //checking for clicked term either agrovoc or agrotag


            try{

                   String[] file_ext=stats1.split("\\.");
                                            System.out.println("file_ext "+file_ext.length);
                                            System.out.println("finally file ext  "+file_ext[1]);
		 String[] exten={"doc","ppt","pdf","docx","pptx","odt","odp"};
                   System.out.println("extensions list array length "+exten.length);


                                            for(int in=0;in<exten.length;in++)
                                            {

                                                if(exten[in].equals(file_ext[1]))
                                                {
                                                   flag=1;
                                                   System.out.println("extension"+exten[in]);
                                                    //out.println("extension"+exten[in]);
                                                   System.out.println("extension original"+file_ext[1]);
                                                   //out.println("extension original"+file_ext[1]);
                                                   break;

                                                }
                                                else
                                                    flag=0;
                                              }
  }
            catch(Exception e)
            {
               out.println("exception in uploaddddddddd"+e.getMessage()) ;
            }

                 if(flag==1)
                 {

                 if(ses.getAttribute("agrovoc")=="agrovoc")
                    {

                        System.out.println("sessssion of jsp   "+ses.getAttribute("agrovoc"));



               try {
                                        /* Create string of connection url within specified format with machine name,
                                        port number and database name. Here machine name id localhost and
                                        database name is usermaster. */
                                        String connectionURL = "jdbc:mysql://localhost:3306/autoTagger";

                                        // declare a connection by using Connection interface
                                        Connection con = null;
                                        Statement stmt=null;
                                        ResultSet rst=null;
                                        ResultSet rst1=null;
                                        int num=0;
                                        String tags=null;
                                        int mnid=0;
                                       

out.println();
out.println();
out.println();
out.println();


                                        // Load JBBC driver "com.mysql.jdbc.Driver"
                                        Class.forName("com.mysql.jdbc.Driver").newInstance();

                                        /* Create a connection by using getConnection() method that takes parameters of
                                        string type connection url, user name and password to connect to database. */
                                        con = DriverManager.getConnection(dbPath);//connectionURL, "staging", "password");

                                        // check weather connection is established or not by isClosed() method
                                        if(!con.isClosed())
                                        System.out.println("Successfully connected to " + "MySQL server using TCP/IP...");

                                        stmt=con.createStatement();

                                        System.out.println("hellllllllllooooooooooo in tagger.jsp");

                                          rst1=stmt.executeQuery("SELECT max(nid) as nid FROM node ");
                                            while(rst1.next())
                                            {
                                               mnid=rst1.getInt("nid");
                                             //out.println("nid:::::::::::::  "+mnid);
                                            }

                                                   // mnid++;

                                          System.out.println("mnidd "+mnid);



                                        rst=stmt.executeQuery("SELECT agrovoc_tags FROM node where nid="+mnid);
                                            while(rst.next())
                                            {
                                               tags=rst.getString("agrovoc_tags");
                                              System.out.println("tags:::::::::::::  "+tags);
                                              
                                              if(tags==null)
                                              {

                                                  ttt="blank";
                                                    //out.println("<html><head><script language='javascript'> document.getElementById('process').innerHTML = ''; document.getElementById('messageDiv').innerHTML = '';</script></head><body>File Format not supported</body></html>");
                                                 // flag=1;
                                                 // break;
                                                 // out.println("<br/><br/><br/><font size='4'><b>Please check your file format</b></font>");
                                                 // break;
                                                    // out.println("<br/><br/><br/><font size='4'><b>Please check your file format</b></font>");
                                                    // response.getOutputStream().print("<html><head><script type='text/javascript'>function killUpdate()");
                                                    // response.getOutputStream().print("{ window.parent.killUpdate(); }</script></head><body onload='killUpdate();'></body></html>");
                                                    
                                              }
                                                else
                                                {
                                                //out.println("<script language=\"javascript\"> document.getElementById('process').innerHTML = '';</script>");
                                                out.println("<br/><br/><br/><font size='4'><b>Agrovoc:</b>  "+tags+"</font>");
                                                }
                                            }
                                             con.close();
                                            
                                            

                                        }
                                       catch(Exception ex)
                                        {
                                        System.out.println("exception in connection "+ex.getMessage());




                                        }
                     }
                  else
                      if(ses.getAttribute("agrotag")=="agrotag")
                         {
                          System.out.println("sessssion of jsp   "+ses.getAttribute("agrotag"));

                          try {
                                        /* Create string of connection url within specified format with machine name,
                                        port number and database name. Here machine name id localhost and
                                        database name is usermaster. */
                                        String connectionURL = "jdbc:mysql://localhost:3306/autoTagger";

                                        // declare a connection by using Connection interface
                                        Connection con = null;
                                        Statement stmt=null;
                                        ResultSet rst=null;
                                        ResultSet rst1=null;
                                        int num=0;
                                        String tags=null;
                                        int mnid=0;


out.println();
out.println();
out.println();
out.println();


                                        // Load JBBC driver "com.mysql.jdbc.Driver"
                                        Class.forName("com.mysql.jdbc.Driver").newInstance();

                                        /* Create a connection by using getConnection() method that takes parameters of
                                        string type connection url, user name and password to connect to database. */
                                        con = DriverManager.getConnection(dbPath);//connectionURL, "root", "gaurav");

                                        // check weather connection is established or not by isClosed() method
                                        if(!con.isClosed())
                                        System.out.println("Successfully connected to " + "MySQL server using TCP/IP...");

                                        stmt=con.createStatement();

                                        System.out.println("hellllllllllooooooooooo in tagger.jsp");

                                          rst1=stmt.executeQuery("SELECT max(nid) as nid FROM node ");
                                            while(rst1.next())
                                            {
                                               mnid=rst1.getInt("nid");
                                              // out.println("tags:::::::::::::  "+tags);
                                            }

                                                   // mnid++;

                                          System.out.println("mnidd "+mnid);



                                        rst=stmt.executeQuery("SELECT agro_tags FROM node where nid="+mnid);
                                            while(rst.next())
                                            {
                                               tags=rst.getString("agro_tags");
                                              System.out.println("tags:::::::::::::  "+tags);

                                              if(tags==null)
                                              {

                                                  ttt="blank";
                                                  System.out.println("tags not generated "+tags);
                                                    //out.println("<html><head><script language='javascript'> document.getElementById('process').innerHTML = ''; document.getElementById('messageDiv').innerHTML = '';</script></head><body>File Format not supported</body></html>");
                                                 // flag=1;
                                                 // break;
                                                 // out.println("<br/><br/><br/><font size='4'><b>Please check your file format</b></font>");
                                                 // break;
                                                    // out.println("<br/><br/><br/><font size='4'><b>Please check your file format</b></font>");
                                                    // response.getOutputStream().print("<html><head><script type='text/javascript'>function killUpdate()");
                                                    // response.getOutputStream().print("{ window.parent.killUpdate(); }</script></head><body onload='killUpdate();'></body></html>");

                                              }
                                                else
                                                {
                                                //out.println("<script language=\"javascript\"> document.getElementById('process').innerHTML = '';</script>");
                                                out.println("<br/><br/><br/><font size='4'><b>Agrotags:</b>  "+tags+"</font>");
                                                }
                                            }
                                             con.close();
                                             


                                        }
                                       catch(Exception ex)
                                        {
                                        System.out.println("exception in connection "+ex.getMessage());
                                        }

                         }

                }
 else
            out.println("<br/><br/><br/><font size='4'>Please Check File Format of Uploaded Document </font>");
               
            }
            // HttpSession theSession = request.getSession( false );

    
            
        // invalidating a session destroys it
          //  out.println("file uplad stats   "+request.getAttribute("FILE_UPLOAD_STATS"));
        // request.getSession().invalidate();
               //   out.println( "<BR>Session destroyed" );
     

         //    out.println("statssssssssssssssss "+stats);
              
             
                 System.out.println("Finished writing, leaving AjaxUploadStatusServlet");
                
               
           out.flush();
        } else {

        	System.out.println("stats null");
              
        }
    }
}
